<template>
  <!-- 人脸采集页 -->
  <div style="height:100%">
        <navbar :title="$t('facial_information_collection')" :backCallback="backHome"></navbar>
        <div style="padding-top:60px;margin: auto;" class="prize_box_img">
          <img :src="blobUrl?blobUrl:''" alt="" >
        </div>
        <div class="footer">
          <van-button plain type="info" @click="remake">{{$t('re_photo')}}</van-button>
          <van-button type="info" :loading="loading" @click="submitForReview">{{$t('submit_review')}}</van-button>
        </div>
        <!-- h5打开摄像机 -->
        <face-camera
         :photoVisible="photoVisible"
         @changeState="changeState" @witnesState='witnesState'>
        </face-camera>
  </div>
</template>
<script>
import faceInfoCollection from '@/utils/faceInfo';
import { Toast } from 'vant';
import faceCamera from '@/components/faceModal/faceCamera';
export default {
    components: {vanToast: Toast, faceCamera},
    data() {
        return {
            photoVisible: false,
            srcPath: '',
            srcBase64: window.localStorage.getItem('srcBase64'),
            blobUrl: '',
            isiOS: '',
            loading: false
        };
    },
    mounted() {
        let u = navigator.userAgent;
        //android终端
        // let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
        // ios终端;
        this.isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        this.srcPath = window.localStorage.getItem('srcBase64');
        this.blobUrl = this.isiOS ? this.srcPath : this.$route.query.srcPath;
        // const blob = this.base64ImgtoFile(this.srcBase64);
        // this.blobUrl = window.URL.createObjectURL(blob) || window.webkitURL.createObjectURL(blob);
    },
    methods: {
        backHome() {
            this.$router.push({path: '/home'});
        },
        // 重拍
        async remake() {
            const plus = this.$store.state.config.plus ? this.$store.state.config.plus : window.plus;
            const isWechat = /micromessenger/i.test(navigator.userAgent || '');
            if (plus) { // APP人脸采集
                let data = await faceInfoCollection(this);
                this.srcBase64 = data.urlBase;
                localStorage.setItem('srcBase64', data.urlBase);
                const blob = this.base64ImgtoFile(this.srcBase64);
                // 重拍APP
                this.blobUrl = window.URL.createObjectURL(blob) || window.webkitURL.createObjectURL(blob);
            } else if (isWechat) { // 微信公众号采集人脸
                // console.log(location.href, ' location.href');
                // location.href.split('#')[0]
                this.$wx.initConfig(['chooseImage', 'getLocalImgData'], location.href.split('#')[0]).then(() => {
                    this.$wx.faceGather().then(res => {
                        localStorage.removeItem('srcBase64');
                        localStorage.setItem('srcBase64', res.urlBase);
                        this.srcBase64 = res.urlBase;
                        this.blobUrl = this.isiOS ? this.srcBase64 : res.pathSrc[0];
                    });
                }).catch(() => { // 重拍页面错误信息
                });
            } else { // H5
                this.photoVisible = true;
            }
        },
        submitForReview() {
            this.loading = true;
            const isWechat = /micromessenger/i.test(navigator.userAgent || '');
            let datas = {
                // ufgPath: this.isiOS ? this.srcBase64 : `${this.srcBase64}`
                // ufgPath: this.isiOS ? this.srcBase64 : `data:image/jpeg;base64,${this.srcBase64}`
                ufgPath: this.isiOS ? this.srcBase64 : isWechat ? `data:image/jpeg;base64,${this.srcBase64}` : `${this.srcBase64}`
            };
            const rep = this.$route.query.replace;
            if (rep) {
                this.$axios.post('/app/api/trainee/user-face-gather/update', datas).then(res => {
                    if (res) {
                        Toast.success(this.$t('successfully_submitted'));
                        this.loading = false;
                        setTimeout(() => {
                            this.$router.push({path: '/faceInfoPage'});
                        }, 800);
                    }
                });
            } else {
                this.$axios.post('/app/api/trainee/user-face-gather/insert', datas).then(res => {
                    if (res) {
                        Toast.success(this.$t('successfully_submitted'));
                        this.loading = false;
                        setTimeout(() => {
                            this.$router.push({path: '/faceInfoPage'});
                        }, 800);
                    }
                });
            }
        },
        // base64转file
        base64ImgtoFile(srcBase64, filename = 'file') {
            //将base64格式分割：['data:image/png;base64','XXXX']
            const arr = srcBase64.split(',');
            // .*？ 表示匹配任意字符到下一个符合条件的字符 刚好匹配到：
            // image/png
            const mime = arr[0].match(/:(.*?);/)[1]; //image/png
            //[image,png] 获取图片类型后缀
            const suffix = mime.split('/')[1]; //png
            const bstr = atob(arr[1]); //atob() 方法用于解码使用 base-64 编码的字符串
            let n = bstr.length;
            const u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], `${filename}.${suffix}`, {
                type: mime
            });
        },
        // 退出人脸抓拍
        changeState(val) {
            this.photoVisible = false;
        },
        // 拍照完成后关闭和恢复时间
        witnesState(value, url, baseUrl) {
            if (baseUrl) {
                localStorage.setItem('srcBase64', baseUrl);
                this.srcBase64 = baseUrl;
                const blob = this.base64ImgtoFile(baseUrl);
                this.blobUrl = window.URL.createObjectURL(blob) || window.webkitURL.createObjectURL(blob);
            }
            this.photoVisible = value;
        }
    }

};
</script>

<style scoped lang="less">
  .footer{
    position: fixed;
    bottom: 0;
    height: 56px;
    background: white;
    width: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
        /deep/.van-button{
            border-radius: 4px;
            height: 40px;
            width: 180px;
        }
        /deep/.van-button--plain{
            width: 80px !important;
        }
        /deep/.van-button--info{
            background-color: #075ebb;
            border: 1px solid #075ebb;
        }
        /deep/.van-button--plain.van-button--info{
            background-color: #fff;
            color: #075ebb;
            border: 1px solid #075ebb;
        }
    }
  .prize_box_img {
    height:300px;
    width:240px;
  }
  .prize_box_img img{
    width: 100%;
    height: 100%;
    margin-top:30px
  }
</style>
